from ..repositories import notification_repositories
from ..repositories.db import get_db_connection

async def send_system_notification(user_id, message, is_warning=0, sender_id=None):
    """
    发送系统通知
    :param user_id: 用户ID
    :param message: 消息内容
    :param is_warning: 消息类型（0:普通 1:警告/拒绝 2:成功/接受）
    :param sender_id: 发送者ID
    :return: 发送结果
    """
    try:
        result = await notification_repositories.send_system_notification(
            user_id, 
            message, 
            is_warning,
            sender_id
        )
        if result:
            return {"code": 0, "message": "发送成功"}
        return {"code": 1, "message": "发送失败"}
    except Exception as e:
        print(f"发送系统通知失败: {str(e)}")
        return {"code": 1, "message": "发送系统通知失败"}

async def get_notifications(user_id, current_page=1, page_size=10):
    """
    获取用户的所有通知，带分页功能
    :param user_id: 用户ID
    :param current_page: 当前页码，从1开始
    :param page_size: 每页显示条数
    :return: 通知列表和总记录数
    """
    try:
        result = await notification_repositories.get_notifications(user_id, current_page, page_size)
        return {
            "code": 0, 
            "data": result['data'],
            "total": result['total']
        }
    except Exception as e:
        print(f"获取通知失败: {str(e)}")
        return {"code": 1, "message": "获取通知失败"}

async def send_family_message(user_id, message):
    """
    发送家庭消息
    :param user_id: 用户ID
    :param message: 消息内容
    :return: 发送结果
    """
    try:
        # 验证消息内容
        if not message or not message.strip():
            return {"code": 1000, "message": "消息内容不能为空"}
            
        if len(message) > 255:  # 限制消息长度
            return {"code": 1000, "message": "消息内容过长"}
            
        result = await notification_repositories.send_family_message(user_id, message)
        if result:
            return {"code": 0, "message": "发送成功"}
        return {"code": 1, "message": "发送失败"}
    except Exception as e:
        print(f"发送家庭消息失败: {str(e)}")
        return {"code": 1, "message": "发送消息失败"}

async def check_new_messages(user_id):
    """
    检查是否有新消息
    :param user_id: 用户ID
    :return: 新消息检查结果
    """
    try:
        status = await notification_repositories.get_user_message_status(user_id)
        if not status:
            return {"code": 0, "newMessages": False}

        last_count = status['last_message_count']
        current_count = status['current_message_count']
        if not current_count:
            await send_system_notification(user_id, "注册成功!", 2)
            await send_system_notification(user_id, "感谢您的使用!", 2)
            return {"code": 1, "data": "新用户登录"}
        
        # 更新数据库中的消息数
        await notification_repositories.update_last_message_count(user_id, current_count)
        
        return {
            "code": 0,
            "newMessages": current_count > last_count,
            "count": current_count - last_count
        }
    except Exception as e:
        print(f"检查新消息失败: {str(e)}")
        return {"code": 1, "message": "检查新消息失败"}

async def send_remove_family_notification(operator_id, target_user_id):
    """
    发送移出家庭的系统通知
    :param operator_id: 操作者ID
    :param target_user_id: 被移出者ID
    :return: 发送结果
    """
    try:
        # 获取操作者用户名
        connection = await get_db_connection()
        async with connection.cursor() as cursor:
            await cursor.execute("SELECT username FROM users WHERE id = %s", [operator_id])
            operator = await cursor.fetchone()
            if not operator:
                return False

            message = f"系统通知：{operator['username']}将你移出家庭"
            result = await notification_repositories.send_system_notification(
                target_user_id, 
                message,
                is_warning=True  # 标记为警告消息，前端显示为红色
            )
            return result
    except Exception as e:
        print(f"发送移出家庭通知失败: {str(e)}")
        return False

async def send_admin_status_notification(target_user_id, username, is_promote):
    """
    发送管理员状态变更的系统通知
    :param target_user_id: 目标用户ID
    :param username: 用户名
    :param is_promote: 是否是升级操作
    :return: 发送结果
    """
    try:
        message = f"系统通知：你已被{'升级为管理员' if is_promote else '降级为普通成员'}"
        result = await notification_repositories.send_system_notification(
            target_user_id, 
            message,
            is_warning=2 if is_promote else 1  # 2表示升级（绿色），1表示降级（红色）
        )
        return result
    except Exception as e:
        print(f"发送管理员状态变更通知失败: {str(e)}")
        return False

async def handle_invite(user_id, notification_id, accept):
    """
    处理家庭邀请
    :param user_id: 用户ID
    :param notification_id: 通知ID
    :param accept: 是否接受
    :return: 处理结果
    """
    try:
        result = await notification_repositories.handle_invite(notification_id, user_id, accept)
        if result:
            return {"code": 0, "message": "操作成功"}
        return {"code": 1, "message": "操作失败"}
    except Exception as e:
        print(f"处理邀请失败: {str(e)}")
        return {"code": 1, "message": "处理邀请失败"}


async def handle_join(user_id, notification_id, accept):
    """
    处理申请加入家庭
    :param user_id: 用户ID
    :param notification_id: 通知ID
    :param accept: 是否接受
    :return: 处理结果
    """
    try:
        result = await notification_repositories.handle_join(notification_id, user_id, accept)
        if result:
            return {"code": 0, "message": "操作成功"}
        return {"code": 1, "message": "操作失败"}
    except Exception as e:
        print(f"处理邀请失败: {str(e)}")
        return {"code": 1, "message": "处理邀请失败"}





